<template>
  <div class="choosePartyA">
    <el-button
      plain
      type="single-number"
      style="margin-left: 10px"
      @click="dialogVisible = true"
      >选择</el-button
    >
    <el-dialog
      title="请选择单位"
      fontWeight="500"
      :visible.sync="dialogVisible"
      width="900px"
      :before-close="beforeClose"
    >
      <div class="dialog-container">
        <div class="ccui-tree-wrapper">
          <el-autocomplete
            clearable
            style="margin: 10px 20px 15px"
            popper-class="tree-table-autocomplete"
            prefix-icon="el-icon-search"
            class="inline-input"
            v-model="keyWord"
            placeholder="定位查找"
            @select="handleSelect"
            :fetch-suggestions="querySearchAsync"
            :scrollBottom="handleScrollBottom"
          >
            <div slot-scope="{ item }">
              <div :title="item.orderName" class="orgName">
                <i :class="setSeachIcon(item)" class="orgIcon"></i>
                <span>{{ item.name }}</span>
              </div>
              <p class="orgFullName" :title="item.orgFullName">
                {{ item.orgFullName }}
              </p>
            </div>
          </el-autocomplete>
          <div class="ccui-tree">
            <el-tree
              style="
                overflow: auto;
                height: calc(60vh - 56px);
                padding-left: 13px;
              "
              class="parent-tree flow-tree"
              v-if="isShowTree && renderTree"
              :load="loadNode"
              lazy
              highlight-current
              ref="tree"
              :node-key="nodeKey"
              :check-strictly="true"
              :default-expanded-keys="expandedKeys"
              :props="props"
              @node-click="handleNodeClick"
            >
              <span class="custom-tree-node" slot-scope="{ node }">
                <span>
                  <i
                    class="icon-ccui-unit"
                    style="color: #0089ef"
                    v-if="node.data.orgType === '1'"
                  ></i>
                  <i
                    class="icon-ccui-organization"
                    style="color: #0089ef"
                    v-else
                  ></i>
                  {{ node.label }}
                </span>
              </span>
            </el-tree>
          </div>
        </div>
        <div class="dialog-container-right">
          <p class="chooseCheck">
            {{ "已选择单位" + "&nbsp;(" + selected.length + "个)" }}
          </p>
          <p style="height: 1px; width: 100%; background-color: #f1f1f1"></p>
          <div class="choseContent">
            <ul class="choseSelect">
              <template v-for="(item, index) in selected">
                <li :key="index">
                  <i
                    style="margin-right: 5px"
                    :style="{
                      color: '#0089EF',
                      position: 'absolute',
                      top: 2 + 'px'
                    }"
                    :class="setSeachIcon(item)"
                  ></i>
                  <span class="yname">{{ item.name }}</span>
                  <span
                    class="el-icon-close close"
                    @click="deleteClass(index)"
                  ></span>
                </li>
              </template>
            </ul>
          </div>
        </div>
      </div>
      <div size="mini" type="default-mini" slot="footer" class="dialog-footer">
        <el-button size="mini" type="default-mini" @click="centerDialog"
          >取消</el-button
        >
        <el-button
          size="mini"
          type="primary-font-mini"
          @click="centerTrueDialog"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getQryTree, queryMemberGroup } from "@/basa/api";

export default {
  name: "choosePartyA",
  props: {
    requestResultDataConfig: {
      type: String,
      default: "data"
    },
    nodeKey: {
      type: String,
      default: "partyId"
    },
    requestSeachContent: {
      type: String,
      default: "branchName"
    },
    props: {
      type: Object,
      default: () => {
        return {
          label: "name",
          children: "child",
          isLeaf: "isLeaf"
        };
      }
    },
    setSelectedIcon: {
      type: Function,
      default: () => {}
    },
    selectedData: {
      type: Array,
      default: () => {
        return [];
      }
    },
    isselectedData: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      Title: "",
      choseTitle: "",
      dialogVisible: false,
      selectNumber: "",
      defaultProps: {
        label: "name",
        isLeaf: "isLeaf"
      },
      expendedKey: [],
      selected: [],
      treeData: [],
      expandedKeys: [],
      expandArr: [],
      firstCode: "",
      selectedCode: [],
      level: "",
      orgTypes: 3,
      ids: "",
      renderTree: true,
      positionType: "", // positionType为分支管理/成员管理区分单位、部门的状态
      positionTypes: "", // positionTypes为分支管理区分单位、部门的状态
      // positionManayTypes: "", // 批量上传
      label: "",
      orginName: "",
      departId: "",
      node: "",
      treeId: "", // 成员管理新增单位给部门传的id
      dOrgId: "", // 成员管理修改单位给部门传的id
      memId: "", // 负责人传的id
      peopleOrgType: "", //分支类型编辑页面分支类型 目的是根据单位和部门给负责人传不同的入参
      mindId: "",
      keyWord: "",
      // 树数据
      isShowTree: true,
      orgType: "", //接口返回的值，用它来判断树上的logo图标
      seachItemCode: "", //保存每次拿到的autocode
      groupId: "",
      requestSeachParams: {
        flag: 3,
        branchName: "",
        orgID: "",
        id: ""
      }
    };
  },
  watch: {
    dialogVisible(arr) {
      this.renderParams = this.requestTreeParams;
      this.selectedCode = this.selectedData.map(item => item.autoCode);
      this.selected = []; //清空的原因是一个页面有单位和部门，需要在弹窗弹起来的时候先把原来的清空，然后再注入新的元素
      const res = new Map();
      this.selected = this.isselectedData.filter(
        a => !res.has(a.name) && res.set(a.name, 1)
      ); //编辑的时候，原来本身有的部门，再选的时候会重复，所以要去重
      this.expandArr = [];
      this.expandedKeys = [];
    },
    // input框输入记录
    selectNumber(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    setSeachIcon(i) {
      let arr = [
        "icon-ccui-organization",
        "icon-ccui-unit",
        "icon-ccui-man-hollow",
        "icon-ccui-woman-hollow"
      ];
      let keyClass = "";
      keyClass = arr[0];
      return keyClass;
    },
    querySearchAsync(queryString, cb) {
      this.keyWord = queryString;
      let params = this.requestSeachParams;
      params[this.requestSeachContent] = queryString;
      // params.pageNo = 1;
      queryMemberGroup(params)
        .then(res => {
          cb(res.data.data.rows);
        })
        .catch(e => {});
    },
    handleScrollBottom(data, callback) {
      let params = this.requestSeachParams;
      params[this.requestSeachContent] = this.keyWord;
      queryMemberGroup(params)
        .then(res => {
          let dataRows = res.data.data.rows;
          if (dataRows.length !== 0) {
            callback(dataRows);
          }
        })
        .catch(e => {});
    },
    iconClass(i) {
      let arr = [
        "icon-ccui-organization",
        "icon-ccui-unit",
        "icon-ccui-man-hollow",
        "icon-ccui-woman-hollow"
      ];
      let keyClass = "";
      if (i.orgType === "2") {
        keyClass = arr[Number(i.orgType) + Number(i.sex) - 1];
      } else {
        keyClass = arr[i.orgType];
      }

      let obj = {};
      obj[keyClass] = true;
      return obj;
    },
    handleSelect(seachItem) {
      this.seachItemCode = seachItem.autoCode;
      this.selectedCode.includes(seachItem.autoCode) ||
        this.selectedCode.push(seachItem.autoCode);
      this.formatSelectedData(this.selectedCode);
      this.$nextTick(() => {
        this.setIsSelected(this.expandArr);
      });
    },
    formatSelectedData(arr) {
      if (arr.length < 0) {
        return false;
      }
      let firstCode = this.firstCode;
      arr.forEach(item => {
        let codeItem = item.split("-");
        let index = codeItem.indexOf(firstCode);
        let newcodeArr = codeItem.slice(index);
        let [lastItem] = newcodeArr.slice(-1);
        if (lastItem === "") {
          newcodeArr = newcodeArr.slice(0, -2);
        }
        newcodeArr.forEach(code => {
          if (!this.expandedKeys.includes(code)) {
            this.expandedKeys.push(code);
          }
        });
      });
    },
    // 取消
    centerDialog() {
      this.selected = [];
      this.keyWord = "";
      this.dialogVisible = false;
    },
    // 确定
    centerTrueDialog() {
      if (this.selected.length !== 0) {
        // 根据弹窗显示的给父组件传值过去
        this.$emit(
          "selectPartyA",
          this.selected.length > 0 ? this.selected : this.selected[0],
          this.orgTypes,
          this.orginName,
          this.node
        );
        this.dialogVisible = false;
      } else {
        // this.$message({
        //   message: "请选择单位",
        //   type: "error",
        //   duration: 0,
        //   ccuiCustom: true,
        //   showClose: true,
        //   offset: document.body.clientHeight / 2 - 500
        // });
        this.$showErrorMessage("请选择单位");
      }
      this.selected = [];
      this.keyWord = "";
    },
    // 点击任意地方
    beforeClose() {
      this.dialogVisible = false;
    },
    // 树接口
    loadNode(node, resolve) {
      if (node.level === 0) {
        this.getData().then(res => {
          this.data = res.data.data;
          this.groupId = String(res.data.data[0].groupId);
          this.treeData = res.data[this.requestResultDataConfig];
          this.firstCode =
            this.treeData[0].partyId !== "" && this.treeData[0].partyId;
          if (this.selectedCode.length > 0) {
            this.formatSelectedData(this.selectedCode);
          } else {
            this.treeData.forEach(item => {
              this.expandedKeys.push(item.partyId);
            });
          }
          this.treeData.forEach(item => {
            this.expandedKeys.push(item.partyId);
          });
          this.expandArr.push(...this.treeData);
          resolve(this.treeData);
        });
      }

      if (node.level > 1) {
        this.getData({
          parentId: node.data.partyId,
          flag: this.orgTypes
        }).then(res => {
          let resolveData =
            res.data[this.requestResultDataConfig][0][this.props.children];
          this.setIsSelected(resolveData);
          this.expandArr.push(...resolveData);
          resolve(resolveData);
        });
      }

      if (node.level === 1) {
        let that = this;
        setTimeout(() => {
          let data = [];
          data = that.data[0].child;
          resolve(data);
        }, 500);
      }
    },
    getData(
      params = {
        flag: this.orgTypes,
        parentId: ""
      }
    ) {
      return getQryTree(params);
    },
    // 选中节点高亮显示且显示在右侧
    setIsSelected(arr) {
      [...arr].map(item => {
        if (item.autoCode === this.seachItemCode) {
          this.selected.pop();
          this.selected.push(item);
          const res = new Map();
          this.selected = this.selected.filter(
            a => !res.has(a.autoCode) && res.set(a.autoCode, 1)
          );
          this.$nextTick(() => {
            this.$refs.tree.setCurrentKey(item.partyId);
          });
          return;
        }
        item.isSelected = false;
      });
    },
    handleNodeClick(data, node) {
      this.node = node;
      this.selected.pop();
      this.selected.push(data);
    },
    arrayRemove(arr, delItem) {
      let condeIndex = this.selectedCode.indexOf(delItem.autoCode);
      this.selectedCode.splice(condeIndex, 1);
      delItem.isSelected = false;
      let index = arr.indexOf(delItem);
      arr.splice(index, 1);
    },
    // 删除按钮
    deleteClass(index) {
      this.selected.splice(index, 1);
    },
    // input 筛选
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    // 重新渲染Tree
    reloadTree() {
      this.renderTree = false;
      this.$nextTick(() => {
        this.renderTree = true;
      });
    }
  }
};
</script>

<style scoped lang="scss">
@import "~@/config/styles/mixin.scss";
@import "~@/config/styles/variables.scss";
.choosePartyA {
  display: inline-block;
}
/deep/ .el-dialog__title {
  font-size: 14px;
  color: #4a4a4a;
  font-family: 苹方-简 中黑体;
  font-weight: bold;
}

.dialog-container {
  margin: 0 auto;
  height: 60vh;
}

.dialog-container-left {
  float: left;
  width: 300px;
  height: 60vh;
  border: 1px solid #f1f1f1;
}

.dialog-container-right {
  width: 380px;
  height: 60vh;
  border: 1px solid #f1f1f1;
  float: right;
}

.tree-nav {
  width: 300px;
  height: 60vh;
  overflow: auto;
}

.tree-nav-this {
  padding-left: 20px;
  padding-top: 26px;
  width: 280px;
  height: calc(60vh - 26px);
  overflow: auto;
}

.chooseCheck {
  width: 220px;
  font-weight: 500;
  color: #4a4a4a;
  font-size: 13px;
  margin: 10px 20px;
  line-height: 20px;
}

/deep/
  .el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content {
  background-color: transparent;
  color: #0089ef;
  span {
    font-weight: 500;
  }
}

.choseContent {
  min-height: 49vh;
  max-height: 54vh;
  overflow-y: auto;
}

.choseSelect {
  margin: 20px;
  li {
    font-size: 13px;
    line-height: 18px;
    margin: 0;
    padding: 0 0 12px;
    position: relative;
    .yname {
      display: inline-block;
      width: 245px;
      padding-left: 20px;
    }
  }

  .imgChose {
    display: inline-block;
    width: 6px;
    position: absolute;
    top: 0;
    left: -15px;
  }

  .abbrName {
    display: inline-block;
    width: 88%;
    height: 100%;
    font-size: 13px;
    margin-left: 6px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
/deep/ .close {
  position: absolute !important;
  right: 0px;
  vertical-align: -3px;
  padding-top: 3px;
  display: none;
}

li:hover .close {
  display: inline-block;
}

/deep/ .el-dialog {
  border-radius: 0 !important;
}

/deep/ .el-dialog__title {
  font-size: 14px;
  padding: 0 0 0 20px;
  font-weight: bold;
}

/deep/ .el-dialog__header {
  border-bottom: 1px solid #f1f1f1;
  height: 25px;
  line-height: 25px;
  padding: 0;
}

/deep/ .el-dialog__footer {
  border-top: 1px solid #f1f1f1 !important;
  height: 50px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  text-align: right;
}

/deep/ .el-tree-node__label {
  font-size: 13px;
}

/deep/ .el-button {
  font-size: 13px;
}

/deep/ .el-dialog__body {
  padding: 20px;
  color: #4a4a4a;
  font-size: 13px;
  word-break: break-all;
  min-height: 40px;
}

/deep/ .el-icon-close {
  top: 0px;
}

.ccui-tree-wrapper {
  position: absolute;
  width: 450px;
  height: 60vh;
  background-color: #fff;
  border: 1px solid #f1f1f1;
  .el-tree--highlight-current
    .el-tree-node.is-current
    > .el-tree-node__content {
    background-color: #fff;

    span {
      color: #0089ef !important;
    }
  }
  .custom-tree-node {
    span {
      width: 106px;
      height: 18px;
      font-size: 13px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: rgba(74, 74, 74, 1);
      line-height: 18px;
    }
  }
}

/deep/ .el-dialog__headerbtn .el-icon-close {
  font-size: 16px;
}

// 下拉框样式
.orgName {
  line-height: 18px;
}
.orgName span {
  font-size: 13px;
  color: #4a4a4a;
}
.orgFullName {
  line-height: 18px;
  margin-top: 5px;
  font-size: 13px;
  color: #999999;
  margin-left: 17px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.orgIcon {
  color: #0089ef;
  margin-right: 5px;
}

/deep/.inline-input {
  div {
    width: 220px !important;
  }
}
/deep/ .el-input--prefix .el-input__inner {
  width: 410px !important;
}
/deep/ .el-input__suffix {
  right: -190px;
}
</style>
